<?php
/**
 * Controller for the Tutorial-Model
 *
 * PHP versions 4 and 5
 *
 * TutoriumBase (http://tutoriumbase.my-reality.de)
 * Copyright 2012, Miguel Gonzalez (http://my-reality.de)
 *
 *
 * @copyright     Copyright 2012, Miguel Gonzalez (http://my-reality.de)
 * @link          http://tutoriumbase.my-reality.de TutoriumBase
 * @since         TutoriumBase v 0.1
 */

class TutorialsController extends AppController {
    
    var $name = 'Tutorials';
   
    /**
     * Show all tutorials
     * 
     * ## special
     * 
     * - `listweek` Show only the new tutorials of the current week
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function index($special = '') {        
        $params = array();        
        $caption = 'Alle Tutorials';        
        
        if ($special == 'listweek') {
            $params['order'] = 'Tutorial.created ASC';
            $params['limit'] = 5;
            $caption = 'Tutorials der Woche';
        }
        
        // Find the tutorials
        $tutorials = $this->Tutorial->find('all', $params);                
        
        if (empty($tutorials)) {
            // No data -> redirect
            $this->flashMessage('Es gibt noch keine Tutorials.', 'fail');
            $this->redirect(array(
                 'controller' => 'pages', 
                 'action' => 'about')
            );
        }
        
        // Searching for categories
        foreach ($tutorials as &$tutorial) {
            // Sort chapter
            $tutorial['Chapter'] = Set::sort($tutorial['Chapter'], '{n}.inner_order', 'asc');            
            foreach ($tutorial['CategoryCount'] as $catcount) {
                $tutorial['Category'][] = $this->Tutorial->CategoryCount->Category->findById($catcount['category_id']);
            }
        }
        
        // Set data
        $this->set('tutorials', $tutorials);
        $this->setPageTitle($caption);
    }
    
    
    
    
    
    /**
     * Find data of the search query
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function search() {
        // If search content is invalid -> Break searching
        if (empty($this->data) || ($this->data['Tutorial']['searchword'] == 'Tutorial suchen...' && $this->data['Tutorial']['category'] == 'Kategorie')) {
            $this->flashMessage('Sie müssen ein Suchbegriff eingeben!', 'fail');
            $this->redirect(array('controller' => 'tutorials', 'action' => 'index'));
        }
        
        // Specialize the search
        $conditions = array();
        $results = array();
        
        if ($this->data['Tutorial']['searchword'] != 'Tutorial suchen...' && $this->data['Tutorial']['category'] == 'Kategorie') {
            $conditions['Tutorial.caption LIKE'] = '%' . $this->data['Tutorial']['searchword'] . '%';
        } else {
            
        }
        
        // Find results
        $results = $this->Tutorial->find('all', array('conditions' => $conditions));

        // Find categories
        foreach ($results as &$tutorial) {
            $tutorial['Chapter'] = Set::sort($tutorial['Chapter'], '{n}.Chapter.inner_order', 'asc');            
            foreach ($tutorial['CategoryCount'] as $catcount) {
                $tutorial['Category'][] = $this->Tutorial->CategoryCount->Category->findById($catcount['category_id']);
            }
        }
        
        $this->set('tutorials', $results);
        
        if (empty($results)) {
            if ($this->data['Tutorial']['category'] != 'Kategorie' && $this->data['Tutorial']['searchword'] == 'Tutorial suchen...') {
                $this->flashMessage('Die Suche nach der Kategorie "' . $this->data['Tutorial']['category'] . '" ergab 0 Treffer.', 'fail');                
            } else {
                $this->flashMessage('Die Suche nach dem Begriff "' . $this->data['Tutorial']['searchword'] . '" ergab 0 Treffer.', 'fail');
            } 
            
            $this->redirect($this->referer());
        } else {
            $this->flashMessage('Ihre Suche ergab ' . count($results) . ' Treffer.', 'success');
        }    
        
        $this->setPageTitle('Suchergebnisse');    
        $this->set('caption', 'Tutorials - Suchergebnisse');
    }
    
    
    
    
    
    /**
     * Create a new tutorial
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function add() {
        if (!empty($this->data)) {
            
            $new_chapter = array();
            $new_cat_count = array();
            
            // Edit chapter data           
            $new_chapter['Chapter']['caption'] = $this->data['Tutorial']['chapter_caption'];
            $new_chapter['Chapter']['content'] = $this->data['Tutorial']['content'];
            $new_chapter['Chapter']['inner_order'] = 1;
            
            // Create category counter
            $new_cat_count['CategoryCount']['category_id'] = $this->data['Tutorial']['category'];
            
            // Sanitize data
            $this->data['Tutorial']['user_id'] = $this->Session->read('Auth.User.id');            
            $this->data['Tutorial']['caption'] = Sanitize::html($this->data['Tutorial']['caption'], array('remove' => true));
            $this->data['Tutorial']['description'] = Sanitize::html($this->data['Tutorial']['description'], array('remove' => true));
            
            // Save data
            if ($this->Tutorial->save($this->data)) {
                 $new_cat_count['CategoryCount']['tutorial_id'] = $this->Tutorial->id;                 
                 $new_chapter['Chapter']['tutorial_id'] = $this->Tutorial->id;              
                 
                 if ($this->Tutorial->CategoryCount->save($new_cat_count) &&
                     $this->Tutorial->Chapter->save($new_chapter)) {
                     $this->flashMessage('Tutorial wurde erfolgreich erstellt!', 'success');
                     
                     // Redirect
                     $this->redirect(array(
                          'controller' => 'users', 
                          'action'     => 'view/' . $this->Session->read('Auth.User.id'))
                     );
                 } else {
                     $this->flashMessage('Hupps! Da ist etwas schief gelaufen. Bitte probiere es erneut.', 'fail');
                     $this->redirect('/');
                 }

            } else {
                $this->flashMessage('Es sind ein oder mehrere Fehler aufgetreten!', 'fail');
            }
        } 
        
        // Set data
        $this->set('caption', 'Neues Tutorial');
        $this->setPageTitle('Neues Tutorial');  
    }
    
    
    
    
    
    /**
     * Edit the tutorial with the given id
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function edit($id = null) {
        $this->Tutorial->id = $id; 
       
       if (empty($this->data)) {
           // Load tutorial data
           $this->data = $this->Tutorial->read();
           
           // Only owner has the permission to edit
           if ($this->data['User']['id'] != $this->Session->read('Auth.User.id')) {
               // No rights -> redirect
               $this->redirect(array(
                    'controller' => 'tutorials', 
                    'action' => 'index')
               );
           } 
       } else {
           /** @todo At the moment only 1 category available! */
           $category = $this->data['Tutorial']['category'];
           
           // Santitize data
           $this->data['Tutorial']['caption'] = Sanitize::html($this->data['Tutorial']['caption'], array('remove' => true));
           $this->data['Tutorial']['description'] = Sanitize::html($this->data['Tutorial']['description'], array('remove' => true));
           
           // Save data
           if ($this->Tutorial->save($this->data)) {               
               // Find categories
               $cat_data = $this->Tutorial->CategoryCount->findByTutorialId($this->Tutorial->id);
               $cat_data['CategoryCount']['category_id'] = $category;
               
               // Save categories
               if ($this->Tutorial->CategoryCount->save($cat_data))
               {
                   $this->flashMessage('Tutorial wurde erfolgreich geändert.', 'success');
                   $this->redirect($this->referer(array(
                        'action' => 'index'))
                   );
               } else {
                   $this->flashMessage('Fehler beim Speichern.', 'fail');
               }   
           } else {
               $this->flashMessage('Fehler beim Speichern.', 'fail');
           }
       }
       
       // Set data
       $this->set('caption', 'Tutorial bearbeiten');
       $this->setPageTitle('Tutorial bearbeiten');  
    }
    
    
    
    
    /**
     * Edit the tutorial with the given id
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function view($id, $chapter_id = null) {
        $tutorial = $this->Tutorial->findById($id);

        if (!empty($tutorial)) {            
            if (empty($chapter_id)) {
                $this->redirect(array(
                     'controller' => 'tutorials', 
                     'action' => 'view/' . $tutorial['Tutorial']['id'] . '/1')
                );
            }
            
            // Set chapter         
            $chapter = $this->Tutorial->Chapter->findByInnerOrder($chapter_id);
            
            if (empty($chapter)) {
                $this->redirect(array('controller' => 'tutorials', 'action' => 'index'));
            }              
                                    
            /** @todo TODO: Allow html tags */
            foreach($tutorial['Chapter'] as $value) {
                if ($value['inner_order'] == $chapter['Chapter']['inner_order']) {
                    $chapter['Chapter'] = $value;
                    break;
                }
            }

            $tutorial['Chapter'] = Set::sort($tutorial['Chapter'], '{n}.inner_order', 'asc');            
                       
            // Searching for categories
            foreach ($tutorial['CategoryCount'] as $catcount) {
                  $this->Tutorial->CategoryCount->Category->id = $catcount['category_id'];
                  $tutorial['Category'][] = $this->Tutorial->CategoryCount->Category->read();
            }
            
            // Set data
            $this->set('tutorial', $tutorial);
            $this->set('chapter', $chapter);
            $this->setPageTitle($tutorial['Tutorial']['caption']); 
            //$this->set('rightbox', $layout->generateTutorialFeatures($tutorial,$chapter['Chapter']['inner_order']));
        } else {
            // No data -> redirect
            $this->redirect(array('controller' => 'tutorials', 'action' => 'index'));
        }
    }
    
    
    
    
    /**
     * Remove the tutorial with the given id
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function delete($id) {
        $tutorial = $this->Tutorial->findById($id);
        
        if (!empty($tutorial)) {

            // Delete all chapters
            foreach ($tutorial['Chapter'] as $chapter) {
                $this->Tutorial->Chapter->delete($chapter['id']);
            }

            // Delete category entries
            foreach ($tutorial['CategoryCount'] as $category) {
                $this->Tutorial->CategoryCount->delete($category['id']);
            }        

            // Delete tutorial
            if ($this->Tutorial->delete($id)) {
                $this->flashMessage('Tutorial erfolgreich gelöscht.', 'success');
                $this->redirect($this->referer());
            }
        }         
        
        // Success
        $this->flashMessage('Tutorial konnte nicht gelöscht werden.', 'success');        
        $this->redirect($this->referer());
    }
}
?>
